<template>
	<view class="content">
		<view class="cropper-wrapper">
			<canvas
				class="cropper"
				disable-scroll="true"
				@touchstart="handleTouchStart"
				@touchmove="handleTouchMove"
				@touchend="handleTouchEnd"
				canvas-id="cropper"
				ref="cropperCanvas"
			></canvas>
		</view>

		<view class="preview-container" v-if="localUrl">
			<text class="preview-tip">裁剪预览（圆形）</text>
			<view class="preview-avatar">
				<image :src="localUrl" mode="aspectFill" class="preview-img"></image>
			</view>
		</view>

		<view class="cropper-buttons">
			<view class="upload" @tap="uploadTap">重新选择</view>
			<view class="getCropperImage" @tap="getCropperImage" :class="{ disabled: loading || !cropper }">确定</view>
		</view>
	</view>
</template>

<script>
import weCropper from './weCropper.js';

export default {
	data() {
		return {
			cropper: null,
			localUrl: "",
			loading: false,
			deviceInfo: {},
			cutSize: 0,
			canvasReady: false // 标记Canvas是否就绪
		};
	},
	// onLoad：仅获取参数，不初始化Canvas相关逻辑
	onLoad(option) {
		this.deviceInfo = uni.getSystemInfoSync();
		this.cutSize = Math.floor(this.deviceInfo.windowWidth * 0.6);
		this.pageOption = option; // 暂存参数
	},
	// onReady：页面渲染完成（Canvas挂载）后再初始化
	onReady() {
		this.initCropper();
	},
	onUnload() {
		this.cropper = null;
		this.canvasReady = false;
	},
	methods: {
		// 初始化裁剪实例（延迟到onReady后）
		initCropper() {
			const that = this;
			// 确保Canvas渲染完成，延迟100ms兜底
			setTimeout(() => {
				const canvasWidth = that.deviceInfo.windowWidth;
				const canvasHeight = that.deviceInfo.windowHeight - 50 - (that.deviceInfo.safeAreaInsets?.bottom || 0) - 40;
				
				that.cropper = new weCropper({
					id: 'cropper',
					width: canvasWidth,
					height: canvasHeight,
					scale: 3,
					zoom: 5,
					cut: { size: that.cutSize },
					src: that.pageOption.src ? decodeURIComponent(that.pageOption.src) : ''
				});
				
				// 监听Canvas就绪状态
				that.cropper.onCanvasReady = function() {
					that.canvasReady = true;
				};
			}, 100);
		},
		// 触摸事件防护：仅Canvas就绪后执行
		handleTouchStart(e) {
			if (!this.canvasReady || !this.cropper) return;
			this.cropper.touchStart(e);
		},
		handleTouchMove(e) {
			if (!this.canvasReady || !this.cropper) return;
			this.cropper.touchMove(e);
		},
		handleTouchEnd(e) {
			if (!this.canvasReady || !this.cropper) return;
			this.cropper.touchEnd(e);
		},
		// 重新选择图片
		uploadTap() {
			if (!this.canvasReady) {
				uni.showToast({ title: '画布未就绪，请稍后', icon: 'none' });
				return;
			}
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const src = res.tempFilePaths[0];
					this.cropper.loadImage(src);
				},
				fail: (e) => {
					console.error('选择图片失败：', e);
					uni.showToast({ title: '选择图片失败', icon: 'none' });
				}
			});
		},
		// 获取裁剪后的图片
		async getCropperImage() {
			if (this.loading || !this.canvasReady || !this.cropper) {
				uni.showToast({ title: '操作不可用，请稍后', icon: 'none' });
				return;
			}
			this.loading = true;
			
			try {
				uni.showLoading({ title: '裁剪中...' });
				this.cropper.getCropperImage((avatarPath) => {
					uni.hideLoading();
					if (!avatarPath) {
						uni.showToast({ title: '裁剪失败', icon: 'none' });
						this.loading = false;
						return;
					}
					
					this.localUrl = avatarPath;
					const eventChannel = this.getOpenerEventChannel();
					eventChannel.emit('acceptDataFromOpenedPage', {
						localUrl: avatarPath,
						success: true
					});
					
					setTimeout(() => {
						uni.navigateBack({ delta: 1 });
					}, 800);
				});
			} catch (e) {
				console.error('裁剪异常：', e);
				uni.hideLoading();
				uni.showToast({ title: '裁剪失败', icon: 'none' });
				this.loading = false;
			}
		}
	}
};
</script>

<style scoped>
.content {
	background: #f0f0f0;
	height: 100vh;
	box-sizing: border-box;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.cropper-wrapper {
	flex: 1;
	position: relative;
}

.cropper {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}

.preview-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin: 15rpx 0;
}

.preview-tip {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.preview-avatar {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	overflow: hidden;
	border: 2rpx solid #04b00f;
}

.preview-img {
	width: 100%;
	height: 100%;
}

.cropper-buttons {
	width: 100%;
	height: 50px;
	display: flex;
	background-color: #000;
}

.cropper-buttons > view {
	flex: 1;
	text-align: center;
	line-height: 50px;
	color: #04b00f;
	font-size: 16px;
}

.cropper-buttons .upload {
	border-right: 1px solid #333;
}

.getCropperImage.disabled {
	opacity: 0.6;
	pointer-events: none;
}
</style>